#include <iostream>
#include <string>
#include <strings.h>
#include <cstring>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "log.hpp"
#include <unistd.h>
#include <pthread.h>

Log log;
void Usage(const std::string &proc)
{
    std::cout << "\n\rUsage: " << proc << " server_ip server_port\n"
              << std::endl;
}
struct ThreadData
{
    struct sockaddr_in server;
    int sockfd;
    std::string serverip;
};
void *send_message(void *args)
{
    ThreadData *td = static_cast<ThreadData *>(args);
    socklen_t slen = sizeof(td->server);
    std::string message;
    while (true)
    {
        std::cout << "Please Enter@ ";
        std::getline(std::cin, message);
        // 1. 数据  2. 给谁发
        sendto(td->sockfd, message.c_str(), message.size(), 0, (struct sockaddr *)(&td->server), slen);
        message.clear();
    }
    close(td->sockfd);
    return nullptr;
}
void *recv_message(void *args)
{
    ThreadData *td = static_cast<ThreadData *>(args);
    char buffer[1024];

    while (true)
    {
        struct sockaddr_in temp;
        socklen_t tlen = sizeof(temp);

        ssize_t s = recvfrom(td->sockfd, buffer, 1023, 0, (struct sockaddr *)&temp, &tlen);
        if (s > 0)
        {
            buffer[s] = 0;
            std::cout << buffer << std::endl;
        }
    }
    return nullptr;
}
// ./udp_client server_ip server_port
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        exit(0);
    }
    std::cout << "如果想重定向到某个终端, 可使用int fd = open(""/dev/pts/0"", O_WRONLY) + dup(fd,2) + cerr输出的方式模拟" << std::endl;
    std::cout << "或者采用cerr输出+ ./demo .... 2>/dev/pts/? 的方式来模拟接收和发送 输出分离" << std::endl;
    std::string serverip = argv[1];
    uint16_t serverport = std::stoi(argv[2]);

    struct ThreadData td;
    td.serverip = serverip;
    bzero(&td.server, sizeof(td.server));
    td.server.sin_family = AF_INET;
    td.server.sin_port = htons(serverport);
    td.server.sin_addr.s_addr = inet_addr(serverip.c_str());

    td.sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (td.sockfd < 0)
    {
        log(Fatal, "socket create err, errno: %d, err string: %s", errno, strerror(errno));
        exit(1);
    }
    log(Info, "socket create success");

    pthread_t recver, sender;
    pthread_create(&recver, nullptr, recv_message, &td);
    pthread_create(&sender, nullptr, send_message, &td);

    pthread_join(recver, nullptr);
    pthread_join(sender, nullptr);

    return 0;
}